package org.shopen.puremvc.view
{
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	import org.shopen.puremvc.ApplicationConstants;
	import org.shopen.puremvc.model.domain.testing.Test;
	import org.shopen.puremvc.view.components.testing.TestBox;

	public class TestBoxMediator extends Mediator
	{
		public static const NAME : String = "TestBoxMediator";
		
		[Bindable]
		protected var id : String;
		
		[Bindable]
		protected var test : Test;
		
		protected function get testbox() : TestBox
		{
			var result : TestBox = viewComponent as TestBox;
			return result;
		}
		
		public function TestBoxMediator(viewComponent:Object, testArg : Test)
		{
			super(NAME +"." + testArg.id, viewComponent);
			this.test = testArg;
		}
		
		override public function onRegister():void
		{
			testbox.addEventListener(TestBox.OPTIONSBOX_CREATED, optionsBoxCreatedListener);			
		}
		
		override public function getMediatorName():String
		{
			return NAME + "." + test.id;
		}
		
		override public function listNotificationInterests():Array
		{
			// TODO: handle check test result, check test failed.
			return [ApplicationConstants.TESTOUT];
		}
		
		override public function handleNotification(notification:INotification):void
		{
			// TODO: handle check test result, check test failed.
			var noteName : String = notification.getName();
			switch(noteName)
			{
				case ApplicationConstants.TESTOUT:
					
					var isCorrect : Boolean = testOut();
					if (isCorrect)
						testbox.setCorrect();
					else
						testbox.setIncorrect();
					break;
			}
		}
		
		protected function optionsBoxCreatedListener(event : Event) : void
		{
			initTestBox();
		}
		
		protected function initTestBox() : void
		{
			testbox.question = test.question;
			testbox.points = test.points;
			testbox.setOptions(test.options.optionsArray);
		}
		
		protected function testOut() : Boolean
		{
			// TODO : connect to testing proxy, and check;
			
			var userAnswer : ArrayCollection = testbox.getUserAnswer();			
			var result : Boolean = test.isCorrect(userAnswer);
			var points : Number = test.getPoints(userAnswer);
			
			sendNotification(ApplicationConstants.TEST_RESULT, points, getMediatorName());
			return result;
		}
	}
}